using Homework8.Models;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;

namespace Homework8.Services
{
    public class LogService
    {
        public List<Log> GetAllLogs()
        {
            List<Log> logs = new List<Log>();
            
            using var connection = DBHelper.GetConnection();
            connection.Open();
            
            string sql = "SELECT * FROM Log ORDER BY LogId DESC";
            using var command = new MySqlCommand(sql, connection);
            using var reader = command.ExecuteReader();
            
            while (reader.Read())
            {
                logs.Add(new Log
                {
                    LogId = reader.GetInt32("LogId"),
                    Operation = reader.GetString("Operation"),
                    TableName = reader.GetString("TableName"),
                    RecordId = reader.IsDBNull(reader.GetOrdinal("RecordId")) ? null : reader.GetInt32("RecordId"),
                    Description = reader.IsDBNull(reader.GetOrdinal("Description")) ? null : reader.GetString("Description"),
                    OperationTime = reader.GetString("OperationTime")
                });
            }
            
            return logs;
        }
        
        public List<Log> GetLogsByTableName(string tableName)
        {
            List<Log> logs = new List<Log>();
            
            using var connection = DBHelper.GetConnection();
            connection.Open();
            
            string sql = "SELECT * FROM Log WHERE TableName = @TableName ORDER BY LogId DESC";
            using var command = new MySqlCommand(sql, connection);
            command.Parameters.AddWithValue("@TableName", tableName);
            
            using var reader = command.ExecuteReader();
            
            while (reader.Read())
            {
                logs.Add(new Log
                {
                    LogId = reader.GetInt32("LogId"),
                    Operation = reader.GetString("Operation"),
                    TableName = reader.GetString("TableName"),
                    RecordId = reader.IsDBNull(reader.GetOrdinal("RecordId")) ? null : reader.GetInt32("RecordId"),
                    Description = reader.IsDBNull(reader.GetOrdinal("Description")) ? null : reader.GetString("Description"),
                    OperationTime = reader.GetString("OperationTime")
                });
            }
            
            return logs;
        }
    }
} 